<template>
  <div class="resource-detail">
    <div class="header">
      <h2>{{ resource?.title || '加载中...' }}</h2>
    </div>

    <el-card class="resource-card">
      <div class="resource-info">
        <p><strong>分类:</strong> {{ categoryMap[resource?.category] || resource?.category || '-' }}</p>
        <p><strong>文件类型:</strong> {{ resource?.fileType || '-' }}</p>
        <p><strong>文件大小:</strong> {{ formatFileSize(resource?.fileSize || 0) }}</p>
        <p><strong>上传时间:</strong> {{ formatTime(resource?.uploadTime) }}</p>
      </div>

      <div class="resource-preview">
        <img v-if="isImage(resource?.fileType)" :src="fileUrl" alt="资源预览" @error="handleFileError" />
        <video v-else-if="isVideo(resource?.fileType)" controls :src="fileUrl" @error="handleFileError">
          <source :src="fileUrl" :type="getVideoMimeType(resource?.fileType)">
        </video>
        <audio v-else-if="isAudio(resource?.fileType)" controls :src="fileUrl" @error="handleFileError">
          <source :src="fileUrl" :type="getAudioMimeType(resource?.fileType)">
        </audio>
        <iframe v-else-if="isPdf(resource?.fileType)" :src="fileUrl" width="100%" height="600px"></iframe>
        <pre v-else-if="isText(resource?.fileType)" class="text-preview">{{ textContent }}</pre>
        <p v-else>暂不支持该文件类型预览，请下载查看。</p>
      </div>

      <div class="button-group">
        <el-button type="success" :loading="downloading" @click="downloadFile">下载</el-button>
        <el-button @click="router.go(-1)">返回</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useResourceStore } from '@/stores/api/resource';
import { ElMessage } from 'element-plus';
import { fetchFile, downloadFile } from '@/stores/util/file';

interface Resource {
  id: number;
  title: string;
  category: string;
  fileType: string;
  fileSize: number;
  uploadTime: string;
  fileUri: string;
}

const route = useRoute();
const router = useRouter();
const resourceStore = useResourceStore();

const resource = ref<Resource | null>(null);
const fileUrl = ref('');
const textContent = ref('');
const downloading = ref(false);

const categoryMap = {
  DOCUMENT: '文档',
  VIDEO: '视频',
  AUDIO: '音频',
  IMAGE: '图片',
};

const isImage = (fileType: string) => ['jpg', 'jpeg', 'png', 'gif'].includes(fileType?.toLowerCase?.());
const isVideo = (fileType: string) => ['mp4', 'webm', 'ogg'].includes(fileType?.toLowerCase?.());
const isAudio = (fileType: string) => ['mp3', 'wav', 'ogg'].includes(fileType?.toLowerCase?.());
const isPdf = (fileType: string) => ['pdf'].includes(fileType?.toLowerCase?.());
const isText = (fileType: string) => ['txt', 'text/plain'].includes(fileType?.toLowerCase?.());

const getVideoMimeType = (fileType: string) => {
  const type = fileType?.toLowerCase?.();
  return type === 'mp4' ? 'video/mp4' : type === 'webm' ? 'video/webm' : 'video/ogg';
};

const getAudioMimeType = (fileType: string) => {
  const type = fileType?.toLowerCase?.();
  return type === 'mp3' ? 'audio/mpeg' : type === 'wav' ? 'audio/wav' : 'audio/ogg';
};

const formatFileSize = (bytes: number) => {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
};

const formatTime = (time: string) => {
  if (!time) return '-';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

const handleFileError = () => {
  ElMessage.error('文件加载失败');
  fileUrl.value = '';
  textContent.value = '无法预览文件内容';
};

const fetchResource = async () => {
  try {
    resource.value = await resourceStore.fetchResourceById(parseInt(route.params.id as string));
    if (resource.value?.fileUri) {
      if (isText(resource.value.fileType)) {
        const response = await fetchFile(resource.value.fileUri, 'text');
        textContent.value = response as string;
      } else {
        fileUrl.value = await fetchFile(resource.value.fileUri, 'blob') as string;
      }
    }
  } catch (error) {
    ElMessage.error('加载资源失败');
    router.go(-1);
  }
};

const downloadFile = async () => {
  if (!resource.value?.fileUri) return;
  downloading.value = true;
  try {
    await downloadFile(resource.value.fileUri, resource.value.title);
  } catch (error) {
    ElMessage.error('下载文件失败');
  } finally {
    downloading.value = false;
  }
};

onMounted(() => {
  fetchResource();
});

onUnmounted(() => {
  if (fileUrl.value) {
    URL.revokeObjectURL(fileUrl.value); // 释放临时 URL
  }
});
</script>

<style scoped>
.resource-detail {
  width: 80%;
  margin: 40px auto 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  color: #333;
  flex-grow: 1;
  text-align: center;
}

.resource-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.resource-info p {
  margin: 10px 0;
  font-size: 16px;
  color: #666;
}

.resource-preview {
  text-align: center;
  margin-bottom: 20px;
}

.resource-preview img {
  max-width: 100%;
  max-height: 600px;
}

.resource-preview video,
.resource-preview audio {
  width: 100%;
}

.resource-preview .text-preview {
  white-space: pre-wrap;
  text-align: left;
  max-height: 600px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #e8e8e8;
  background-color: #f9f9f9;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>